package org.unidata.mdm.rest.v1.draft.converter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Objects;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.unidata.mdm.core.dto.UserDTO;
import org.unidata.mdm.core.service.UserService;
import org.unidata.mdm.draft.type.Draft;
import org.unidata.mdm.rest.v1.draft.ro.DraftRO;
import org.unidata.mdm.system.util.ConvertUtils;

/**
 * @author Mikhail Mikhailov on Sep 11, 2020
 */
@Component
public class DraftConverter {

    @Autowired
    private UserService userService;

    /**
     * Constructor.
     */
    public DraftConverter() {
        super();
    }

    public DraftRO toDraftRO(Draft d) {

        if (Objects.isNull(d)) {
            return null;
        }

        DraftRO result = new DraftRO();
        result.setSubjectId(d.getSubjectId() == null ? null : d.getSubjectId());
        result.setDraftId(d.getDraftId());
        result.setParentDraftId(d.getParentDraftId());
        result.setType(d.getProvider());

        if (Objects.nonNull(d.getOwner())) {

            result.setOwner(d.getOwner());

            UserDTO udto = userService.getUserByName(d.getOwner());
            if (Objects.nonNull(udto)) {
                result.setOwnerFullName(udto.getFullName());
            }
        }

        result.setCreateDate(ConvertUtils.date2LocalDateTime(d.getCreateDate()));
        result.setUpdateDate(ConvertUtils.date2LocalDateTime(d.getUpdateDate()));
        result.setCreatedBy(d.getCreatedBy());
        result.setUpdatedBy(d.getUpdatedBy());
        result.setDescription(d.getDescription());
        result.setTags(CollectionUtils.isEmpty(d.getTags()) ? Collections.emptyList() : new ArrayList<>(d.getTags()));
        result.setEditionsCount(d.getEditionsCount());

        return result;
    }
}
